<script lang="ts" setup>
interface INameList {
  label: string
  value: string
}
interface tableSourceType {
  label: string
  name: string
  valid_bet_amount: string
  rebate_ratio: string
  now_level: string
}
defineOptions({
  name: 'RebateDetail',
})
definePageMeta({
  layout: 'header-back',
  title: 'rebate_rate1',
})

const route = useRoute()
const appStore = useAppStore()
const { currentGlobalCurrency, isLogin } = storeToRefs(appStore)
const { isUnified, name, value, isUnifiedSum } = route.query as any

const { rebateTypeArr, customPlatformName, customFormat } = useRebateData()

const unifiedSum = isUnifiedSum === 'true'
const lableOptionVal = ref(value)
const lableOptionList = ref<typeof rebateTypeArr>([])
const nameOptionVal = ref(decodeURIComponent(name))
const nameOptionList = ref<INameList[]>([])
const tableSource = ref<tableSourceType[]>([])
const currentGlobalCurrency2 = computed(() => {
  if (isLogin.value) {
    return currentGlobalCurrency.value
  }
  else {
    return languageConfig[getCurrentLanguageForFrontend()]?.currency
      ?? (getCurrentLanguageForFrontend() === 'pt-BR' ? 'BRL' : 'USDT')
  }
})
const globalCurrencyCode = computed(() => currencyConfig[currentGlobalCurrency2.value]?.cur)
const columns = computed<Column[]>(() => [
  {
    title: '',
    dataIndex: 'label',
    align: 'center',
    mb: 14,
    headerSlot: 'headerLabel',
    thPaddingX: '0px',
    width: 90,
  },
  !unifiedSum && {
    title: '',
    dataIndex: 'name',
    align: 'center',
    mb: 14,
    headerSlot: 'headerName',
  },
  {
    title: $t('accumulated_bet'),
    mb: 14,
    dataIndex: 'valid_bet_amount',
    align: 'center',
    slot: 'valid_bet_amount',
  },
  {
    title: $t('rebate_rate1'),
    dataIndex: 'rebate_ratio',
    mb: 14,
    align: 'center',
    slot: 'rebate_ratio',
    visible: true,
  },
].filter(Boolean) as Column[])

/**  梯级详情返水接口传的货币 */
const showCurrency = computed(() => {
  if (isUnified === 'true')
    return '0'
  else
    if (supportedCur.includes(globalCurrencyCode.value))
      return globalCurrencyCode.value
    else
      return '706'
})
/** 接口返回的展示货币 */
const currencyCode = ref<string>('')
const isLabelPop = ref(false)
const isNamePop = ref(false)
const showCurrencyCode = computed(() => getCurrencyConfigByCode((currencyCode.value as any)).name)
const { runAsync: runVipRebateTieredConfig, data: VipRebateTieredConfigData, loading: loadTieredRebateConfig } = useRequest(ApiMemberVipRebateTieredConfig)
const { runAsync: runVipRebateTieredSumConfig, data: VipRebateTieredSumConfigData, loading: loadTieredRebateSumConfig } = useRequest(ApiMemberTieredRebateSumConfig)

const labelName = computed(() => lableOptionList.value.filter(item => item.value === lableOptionVal.value)?.[0].label)
const nameName = computed(() => nameOptionList.value.filter(item => item.value === nameOptionVal.value)?.[0].label)
function setAllData(chageName: boolean) {
  const VipRebateData = VipRebateTieredConfigData.value || VipRebateTieredSumConfigData.value
  if (!VipRebateData)
    return
  const data = VipRebateData
  currencyCode.value = data.currency_id

  lableOptionList.value = data.menu.map((id: string) => rebateTypeArr.find(a => id === a.value)).filter(Boolean) as typeof rebateTypeArr
  if (unifiedSum) {
    const nowType = rebateTypeArr.find(a => lableOptionVal.value === a.value)!.label
    const source = data.data.map((item: Record<string, any>) => {
      const rebate_ratio = customFormat(item.r, 3)
      return {
        label: nowType,
        name: '',
        valid_bet_amount: `≥ ${item.vba}+`,
        rebate_ratio,
        now_level: data.vblv as string,
      }
    })
    tableSource.value = source
  }
  else {
    let nameIndex = -1 // 当前平台名字index
    const newName = data.name.map((item: string) => customPlatformName(item))
    if (chageName)
      nameOptionVal.value = newName[0]
    else
      nameOptionVal.value = customPlatformName(nameOptionVal.value)

    // 原始的平台名字
    let originName = ''
    nameOptionList.value = newName.map((item: string, index: number) => {
      if (item === nameOptionVal.value) {
        nameIndex = index
        originName = data.name[index]
      }
      return {
        label: item,
        value: item,
      }
    })
    const nowType = rebateTypeArr.find(a => lableOptionVal.value === a.value)!.label
    const source = data.data.map((item: Record<string, any>) => {
      const rebate_ratio = customFormat(item.r[nameIndex], 3)
      return {
        label: nowType,
        name: nameOptionVal.value,
        valid_bet_amount: `≥ ${item.vba}+`,
        rebate_ratio,
        now_level: (data.vblv as Record<string, any>)?.[originName],
      }
    })
    tableSource.value = source
  }
}

/** 初始化数据 */
async function getData(chageName: boolean) {
  if (unifiedSum)
    await runVipRebateTieredSumConfig({ game_type: lableOptionVal.value, currency_id: showCurrency.value })
  else
    await runVipRebateTieredConfig({ game_type: lableOptionVal.value, currency_id: showCurrency.value })
  setAllData(chageName)
}

watch(lableOptionVal, () => getData(true))
watch(nameOptionVal, () => setAllData(false))
watch(isLogin, () => getData(false))
watch(showCurrency, () => getData(false))

await application.allSettled([getData(false)])
</script>

<template>
  <div class="px-4 pb-4 rebate-detail">
    <div v-show="loadTieredRebateConfig || loadTieredRebateSumConfig" class="h-[20vh] w-full center" />
    <div @touchstart.stop @touchmove.stop>
      <div class=" flex flex-1 flex-col pt-0" @touchstart.stop @touchmove.stop>
        <BaseTable
          :columns="columns" :data-source="tableSource ?? []" :show-out-load="true" :loading="loadTieredRebateConfig || loadTieredRebateSumConfig"
          class="rounded-sm"
          style="font-weight: 600;color: var(--color-text-white-2);"
        >
          <template #headerLabel>
            <BaseButton type="none" class="bg-bg-black-3 min-w-20 py-3 px-2 font-semibold border-bg-black-5 border-[1px] text-text-white-0 text-xs" @click="isLabelPop = true">
              <span class="mr-auto">{{ labelName }}</span>
              <div class="bg-bg-black-5 size-5 center rounded-md">
                <BaseIcon name="uni-arrow-down" style="--tg-base-icon-color: var(--color-text-white-0)" />
              </div>
            </BaseButton>
          </template>
          <template #headerName>
            <BaseButton type="none" class="bg-bg-black-3 py-3 px-2 min-w-20 font-semibold border-bg-black-5 border-[1px] text-text-white-0 text-xs" @click="isNamePop = true">
              <span class="mr-auto">{{ nameName }}</span>
              <div class="bg-bg-black-5 size-5 rounded-md center">
                <BaseIcon name="uni-arrow-down" style="--tg-base-icon-color: var(--color-text-white-0)" />
              </div>
            </BaseButton>
          </template>
          <template #valid_bet_amount="{ record }">
            <div class="center">
              <span class="mr-1">{{ record.valid_bet_amount }}</span>
              <AppCurrencyIcon style="--tg-app-currency-icon-size:0.875rem" :currency-type="showCurrencyCode" />
            </div>
          </template>
          <template #rebate_ratio="{ record, index }">
            <div class="center">
              <div class="relative">
                <span>  {{ record.rebate_ratio }}</span>
                <div
                  v-if="index + 1 == record.now_level"
                  class="now-level absolute left-[50%] -top-6 translate-x-[-50%] rounded-md bg-[#9FE871] px-2 text-xs font-semibold"
                >
                  <span class="relative z-10">{{ $t('current') }}</span>
                </div>
              </div>
            </div>
          </template>
        </BaseTable>
      </div>
    </div>
    <BaseBob v-model:show="isLabelPop" v-model:selected="lableOptionVal" :option="lableOptionList" header="" />
    <BaseBob v-model:show="isNamePop" v-model:selected="nameOptionVal" :option="nameOptionList" header="" />
  </div>
</template>

<style lang="scss" scoped>
.rebate-detail{
    --tg-table-th-padding-x: 1rem;
    --tg-table-th-padding-y: 0;
    --tg-table-th-color: var(--color-text-white-0);
    --tg-table-th-background: transparent;
    --bc-table-th-font-size: 0.75rem;
    --bc-table-td-font-size: 0.75rem;
    :deep(.m-tr:nth-child(2)){
        .m-td:first-child{
            border-radius: 0.25rem 0 0 0;
        }
        .m-td:last-child{
            border-radius: 0 0.25rem 0 0;
        }
    }
}
.now-level{
  color:#232626;
  font-weight: 600;

  // &::after {
  //   content: '';
  //   position: absolute;
  //   left: 50%;
  //   bottom: -5px;
  //   transform: translateX(-50%);
  //   width: 0;
  //   height: 0;
  //   border-left: 8px solid transparent;
  //   border-right: 8px solid transparent;
  //   border-top: 12px solid #f00000;
  // }
}
</style>
